﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Web;

namespace WindowsFormsApplication1
{
    public class Utils
    {
        #region URL请求数据
        /// <summary>
        /// HTTP POST方式请求数据
        /// </summary>
        /// <param name="url">URL.</param>
        /// <param name="param">POST的数据</param>
        /// <returns></returns>
        public static string HttpPost(string url, string param)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "POST";
            //request.ContentType = "application/json";
            request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;
            StreamWriter requestStream = null;
            WebResponse response = null;
            string responseStr = null;

            try
            {
                requestStream = new StreamWriter(request.GetRequestStream());
                requestStream.Write(param);
                requestStream.Close();

                response = request.GetResponse();
                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                requestStream = null;
                response = null;
            }

            return responseStr;
        }

        /// <summary>
        /// HTTP GET方式请求数据.
        /// </summary>
        /// <param name="url">URL.</param>
        /// <returns></returns>
        public static string HttpGet(string url)
        {
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.Method = "GET";
            //request.ContentType = "application/x-www-form-urlencoded";
            request.Accept = "*/*";
            request.Timeout = 15000;
            request.AllowAutoRedirect = false;

            WebResponse response = null;
            string responseStr = null;

            try
            {
                response = request.GetResponse();

                if (response != null)
                {
                    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
                    responseStr = reader.ReadToEnd();
                    reader.Close();
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                request = null;
                response = null;
            }

            return responseStr;
        }

        /// <summary>
        /// 执行URL获取页面内容
        /// </summary>
        //public static string UrlExecute(string urlPath)
        //{
        //    if (string.IsNullOrEmpty(urlPath))
        //    {
        //        return "error1" + urlPath;
        //    }
        //    StringWriter sw = new StringWriter();
        //    try
        //    {
        //        System.Web.HttpContext.Current.Server.Execute(urlPath, sw);
        //        return sw.ToString();
        //    }
        //    catch (Exception ex)
        //    {
        //        return "error" + urlPath + ex.Message;
        //    }
        //    finally
        //    {
        //        sw.Close();
        //        sw.Dispose();
        //    }
        //}
        #endregion

        #region 获得当前绝对路径
        /// <summary>
        /// 获得当前绝对路径
        /// </summary>
        /// <param name="strPath">指定的路径</param>
        /// <returns>绝对路径</returns>
        //public static String GetMapPath(String strPath)
        //{
        //    if (strPath.ToLower().StartsWith("http://"))
        //    {
        //        return strPath;
        //    }
        //    if (HttpContext.Current != null)
        //    {
        //        return HttpContext.Current.Server.MapPath(strPath);
        //    }
        //    else //非web程序引用
        //    {
        //        strPath = strPath.Replace("/", "\\");
        //        if (strPath.StartsWith("\\"))
        //        {
        //            strPath = strPath.Substring(strPath.IndexOf('\\', 1)).TrimStart('\\');
        //        }
        //        return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath);
        //    }
        //}
        #endregion

        #region 返回文件扩展名，不含“.”
        /// <summary>
        /// 返回文件扩展名，不含“.”
        /// </summary>
        /// <param name="_filepath">文件全名称</param>
        /// <returns>string</returns>
        public static string GetFileExt(string _filepath)
        {
            if (string.IsNullOrEmpty(_filepath))
            {
                return "";
            }
            if (_filepath.LastIndexOf(".") > 0)
            {
                return _filepath.Substring(_filepath.LastIndexOf(".") + 1); //文件扩展名，不含“.”
            }
            return "";
        }
        #endregion

        #region 生成日期随机码
        /// <summary>
        /// 生成日期随机码
        /// </summary>
        /// <returns></returns>
        public static string GetRamCode()
        {
            #region 
            System.Threading.Thread.Sleep(10);
            return DateTime.Now.ToString("yyyyMMddHHmmssffff");
            #endregion
        }
        #endregion

        #region 生成新增主键
        /// <summary>
        /// 生成新增主键
        /// </summary>
        /// <returns></returns>
        public static string GetGUID()
        {
            return Guid.NewGuid().ToString();
        }
        #endregion

        #region 过滤特殊字符
        /// <summary>
        /// 过滤特殊字符
        /// </summary>
        /// <param name="Input"></param>
        /// <returns></returns>
        public static string Htmls(string Input)
        {
            if (Input != string.Empty && Input != null)
            {
                string ihtml = Input.ToLower();
                ihtml = ihtml.Replace("<script", "&lt;script");
                ihtml = ihtml.Replace("script>", "script&gt;");
                ihtml = ihtml.Replace("<%", "&lt;%");
                ihtml = ihtml.Replace("%>", "%&gt;");
                ihtml = ihtml.Replace("<$", "&lt;$");
                ihtml = ihtml.Replace("$>", "$&gt;");
                return ihtml;
            }
            else
            {
                return string.Empty;
            }
        }
        #endregion

        #region 生成随机字母字符串(数字字母混和)
        /// <summary>
        /// 生成随机字母字符串(数字字母混和)
        /// </summary>
        /// <param name="codeCount">待生成的位数</param>
        public static string GetCheckCode(int codeCount)
        {
            string str = string.Empty;
            int rep = 0;
            long num2 = DateTime.Now.Ticks + rep;
            rep++;
            Random random = new Random(((int)(((ulong)num2) & 0xffffffffL)) | ((int)(num2 >> rep)));
            for (int i = 0; i < codeCount; i++)
            {
                char ch;
                int num = random.Next();
                if ((num % 2) == 0)
                {
                    ch = (char)(0x30 + ((ushort)(num % 10)));
                }
                else
                {
                    ch = (char)(0x41 + ((ushort)(num % 0x1a)));
                }
                str = str + ch.ToString();
            }
            return str;
        }
        #endregion

        #region 随机数 随机订单
        /// <summary>
        /// 根据日期和随机码生成订单号
        /// </summary>
        /// <returns></returns>
        public static string GetCode()
        {
            string num = DateTime.Now.ToString("yyMMddHHmmss");//yyyyMMddHHmmssms
            return num + Number(2).ToString();
        }

        /// <summary>
        /// 生成随机数字
        /// </summary>
        /// <param name="length">生成长度</param>
        /// <returns></returns>
        public static string Number(int Length)
        {
            return Number(Length, false);
        }

        /// <summary>
        /// 生成随机数字
        /// </summary>
        /// <param name="Length">生成长度</param>
        /// <param name="Sleep">是否要在生成前将当前线程阻止以避免重复</param>
        /// <returns></returns>
        public static string Number(int Length, bool Sleep)
        {
            if (Sleep)
                System.Threading.Thread.Sleep(3);
            string result = "";
            System.Random random = new Random();
            for (int i = 0; i < Length; i++)
            {
                result += random.Next(10).ToString();
            }
            return result;
        }

        #endregion

        #region 读取或写入cookie
        ///// <summary>
        ///// 写cookie值
        ///// </summary>
        ///// <param name="strName">名称</param>
        ///// <param name="strValue">值</param>
        //public static void WriteCookie(string strName, string strValue)
        //{
        //    try
        //    {
        //        HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
        //        if (cookie == null)
        //        {
        //            cookie = new HttpCookie(strName);
        //        }
        //        cookie.Value = UrlEncode(strValue);
        //        HttpContext.Current.Response.AppendCookie(cookie);
        //    }
        //    catch
        //    {

        //    }
        //}

        ///// <summary>
        ///// 写cookie值
        ///// </summary>
        ///// <param name="strName">名称</param>
        ///// <param name="strValue">值</param>
        //public static void WriteCookie(string strName, string key, string strValue)
        //{
        //    HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
        //    if (cookie == null)
        //    {
        //        cookie = new HttpCookie(strName);
        //    }
        //    cookie[key] = UrlEncode(strValue);
        //    HttpContext.Current.Response.AppendCookie(cookie);
        //}

        ///// <summary>
        ///// 写cookie值
        ///// </summary>
        ///// <param name="strName">名称</param>
        ///// <param name="strValue">值</param>
        //public static void WriteCookie(string strName, string key, string strValue, int expires)
        //{
        //    HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
        //    if (cookie == null)
        //    {
        //        cookie = new HttpCookie(strName);
        //    }
        //    cookie[key] = UrlEncode(strValue);
        //    cookie.Expires = DateTime.Now.AddMinutes(expires);
        //    HttpContext.Current.Response.AppendCookie(cookie);
        //}

        ///// <summary>
        ///// 写cookie值
        ///// </summary>
        ///// <param name="strName">名称</param>
        ///// <param name="strValue">值</param>
        ///// <param name="strValue">过期时间(分钟)</param>
        //public static void WriteCookie(string strName, string strValue, int expires)
        //{
        //    HttpCookie cookie = HttpContext.Current.Request.Cookies[strName];
        //    if (cookie == null)
        //    {
        //        cookie = new HttpCookie(strName);
        //    }
        //    cookie.Value = UrlEncode(strValue);
        //    cookie.Expires = DateTime.Now.AddMinutes(expires);
        //    HttpContext.Current.Response.AppendCookie(cookie);
        //}

        ///// <summary>
        ///// 读cookie值
        ///// </summary>
        ///// <param name="strName">名称</param>
        ///// <returns>cookie值</returns>
        //public static string GetCookie(string strName)
        //{
        //    if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null)
        //        return UrlDecode(HttpContext.Current.Request.Cookies[strName].Value.ToString());
        //    return "";
        //}

        ///// <summary>
        ///// 读cookie值
        ///// </summary>
        ///// <param name="strName">名称</param>
        ///// <returns>cookie值</returns>
        //public static string GetCookie(string strName, string key)
        //{
        //    if (HttpContext.Current.Request.Cookies != null && HttpContext.Current.Request.Cookies[strName] != null && HttpContext.Current.Request.Cookies[strName][key] != null)
        //        return UrlDecode(HttpContext.Current.Request.Cookies[strName][key].ToString());

        //    return "";
        //}
        //#endregion

        //#region 字符串编码、解码
        ///// <summary>
        ///// URL字符解码
        ///// </summary>
        //public static string UrlDecode(string str)
        //{
        //    if (string.IsNullOrEmpty(str))
        //    {
        //        return "";
        //    }
        //    return HttpContext.Current.Server.UrlDecode(str);
        //}

        ///// <summary>
        ///// URL字符编码
        ///// </summary>
        //public static string UrlEncode(string str)
        //{
        //    if (string.IsNullOrEmpty(str))
        //    {
        //        return "";
        //    }
        //    str = str.Replace("'", "");
        //    return HttpContext.Current.Server.UrlEncode(str);
        //}
        #endregion

        #region 获取时间戳
        /// <summary>
        /// 获取时间戳
        /// </summary>
        /// <returns></returns>
        public static string GetTimestamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds).ToString();
        }
        #endregion

        #region dataTime最近时间转换中文
        public static string ConvertDateTimeToChinese(DateTime _dtime)
        {
            string msg = _dtime.ToShortDateString();
            if ((DateTime.Now - _dtime).TotalDays <= 1)
            {
                if ((DateTime.Now - _dtime).TotalSeconds <= 60)
                {
                    msg = "刚刚发布";
                }
                else if ((DateTime.Now - _dtime).TotalHours <= 1)
                {
                    msg = "一小时前";
                }
            }
            else if ((DateTime.Now - _dtime).TotalDays >= 1 && (DateTime.Now - _dtime).TotalDays <= 2)
            {
                msg = "昨天";
            }
            return msg;
        }
        #endregion

        #region 通过guid获取字符串
        /// <summary>  
        /// 根据GUID获取16位的唯一字符串  
        /// </summary>  
        /// <param name=\"guid\"></param>  
        /// <returns></returns>  
        public static string GuidTo16String()
        {
            long i = 1;
            foreach (byte b in Guid.NewGuid().ToByteArray())
                i *= ((int)b + 1);
            return string.Format("{0:x}", i - DateTime.Now.Ticks);
        }
        #endregion

        #region 通过guid获取数字
        /// <summary>  
        /// 根据GUID获取19位的唯一数字序列  
        /// </summary>  
        /// <returns></returns>  
        public static long GuidToLongID()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0);
        }
        #endregion

        /// <summary>
        /// 是否为日期
        /// </summary>
        /// <param name="StrSource"></param>
        /// <returns></returns>
        public static bool IsDate(string StrSource)
        {
            return Regex.IsMatch(StrSource, @"^((((1[6-9]|[2-9]\d)\d{2})-(0?[13578]|1[02])-(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})-(0?[13456789]|1[012])-(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})-0?2-(0?[1-9]|1\d|2[0-9]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))-0?2-29-))$");
        }

        /// <summary>
        /// 是否为数字
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static bool IsNum(string Str)
        {
            bool bl = false;
            string Rx = @"^[1-9]\d*$";
            if (Regex.IsMatch(Str, Rx))
            {
                bl = true;
            }
            else
            {
                bl = false;
            }
            return bl;
        }

    }

    public class MD5Util
    {
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="encypStr"></param>
        /// <returns></returns>
        public static String GetMD5(String encypStr)
        {
            String retStr;
            MD5CryptoServiceProvider m5 = new MD5CryptoServiceProvider();

            byte[] inputBye;
            byte[] outputBye;

            inputBye = System.Text.Encoding.Default.GetBytes(encypStr);
            outputBye = m5.ComputeHash(inputBye);

            retStr = System.BitConverter.ToString(outputBye);
            retStr = retStr.Replace("-", "").ToUpper();
            return retStr;
        }
    }
}
